/**
 * 
 */
package com.zte.claa.inficombo.csa.app.a.simulator;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.zte.claa.inficombo.csa.app.comm.csif.CSIFMessageBuilder;
import com.zte.claa.inficombo.csa.app.comm.csif.mina.msg.CSIFMessage;
import com.zte.claa.inficombo.csa.app.util.JsonUtils;

/**
 * @author lyp
 *
 */
public class CSIFSimulatorHandler extends IoHandlerAdapter {
	private  Logger logger = LoggerFactory.getLogger(CSIFSimulatorHandler.class);
	
	private CSIFSimulator simulator;

	public CSIFSimulatorHandler(CSIFSimulator simulator) {
		this.simulator = simulator;
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		logger.info("session created: " + session.getId());
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		logger.info("session opened: " + session.getId());
		// 接收到新建连接，触发数据发送.
		this.simulator.receiveNewSession(session);		
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		logger.info("session closed: " + session.getId());
	}

	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		logger.debug("session idled: " + session.getId());
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		logger.error("exception: " + cause.getMessage(), cause);
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		String jsonMsg = CSIFMessageBuilder.parseMessage((CSIFMessage)message);
		logger.info("session message received: " + session.getId()+ ", msg: " + jsonMsg);
		if (StringUtils.isEmpty(jsonMsg)){   //Dereference null return value
			return;
		}
		try{
			JSONObject json = new JSONObject(jsonMsg);
			String cmd = JsonUtils.getJsonAttrVal(json, "cmd", "");
			if(cmd.equals("heartbeat_ack")){
				return;
			}			
			String cmdseq = JsonUtils.getJsonAttrVal(json, "cmdseq", "1");
			String appeui = JsonUtils.getJsonAttrVal(json, "appeui", null);
			String deveui = JsonUtils.getJsonAttrVal(json, "deveui", null);			
			JSONObject rspJson = new JSONObject();
			rspJson.put("cmd", cmd+"_ack");
			rspJson.put("cmdseq", Integer.parseInt(cmdseq));
			if(appeui != null){
				rspJson.put("appeui", appeui);
			}
			if(deveui != null){
				rspJson.put("deveui", deveui);
			}
			rspJson.put("code", 200);
			rspJson.put("msg", "OK");
			session.write(CSIFMessageBuilder.buildMessage(rspJson.toString()));
		}catch(Exception e){
			logger.error("[Simulator error]"+e.getMessage());
		}		
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		logger.info("session message sent: "+session.getId()+", msg: "+message.toString());
	}

	public void inputClosed(IoSession session) throws Exception {
		logger.info("session = "+session.getId()+": inputClosed!");
		// 避免死循环触发inputClosed()方法。
		session.closeNow();
	}
}
